﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RVEAd.Business;
using RVEAd.Business.Model;
using RVEAd.Infrastructure;

namespace RVEAd.Forms
{
    public partial class FormAddEditClient : Form, IAddEditForm
    {

        private RveBL rveBL = null;

        public bool IsEditMode { get; set; }
        public Client Client { get; set; }


        public FormAddEditClient()
        {
            InitializeComponent();
            this.Load += new EventHandler(FormAddEditClient_Load);
        }

        private void InitCategories()
        {
            comboCategories.DisplayMember = "Category";
            comboCategories.ValueMember = "ID";

            comboCategories.DataSource = rveBL.GetAllCategories();
        }


        void FormAddEditClient_Load(object sender, EventArgs e)
        {
            rveBL = new RveBL();

            InitCategories();

            if (IsEditMode)
            {
                CheckClient();
                PutBOinControlsValue();
            }
        }


        void btnSave_Click(object sender, EventArgs e)
        {
            Save();
        }

     

        private void CheckClient()
        {
            if (Client == null)
            {
                throw new Exception("Nu exista client selectat. Nu se poate edita");
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        public bool ValidateInput()
        {
            if (string.IsNullOrEmpty(tbNume.Text))
            {
                MessageBox.Show("Va rog introduceti numele clientului !", "Eroare", MessageBoxButtons.OK);
                return false;
            }

            return true;
        }

        public void PutBOinControlsValue()
        {
            tbNume.Text = Client.Nume;
            comboCategories.SelectedValue = Client.ClientCategory.ID;
        }
        public void PutControlsValueInBO()
        {
            Client.Nume = tbNume.Text;
        }

        public void Save()
        {
            if (IsEditMode)
            {
                Edit();
            }
            else
            {
                Add();
            }

            this.Close();
        }

        public void Add()
        {
            if (ValidateInput())
            {
                rveBL.AddClient(tbNume.Text, (int)comboCategories.SelectedValue);
            }
        }

        public void Edit()
        {
            CheckClient();

            if (ValidateInput())
            {
                PutControlsValueInBO();
                rveBL.UpdateClient(Client, (int)comboCategories.SelectedValue);
            }
        }
    }
}
